import React, { useState } from 'react';
import {
  SunIcon,
  MoonIcon,
  ComputerDesktopIcon,
  KeyIcon,
  ShieldCheckIcon,
} from '@heroicons/react/24/outline';
import { Button, Input } from '@components/ui';
import { useConfig, useAppActions } from '@stores/appStore';
import { useAppConfig } from '@hooks/useTauri';
import { useTranslation, SUPPORTED_LANGUAGES } from '../i18n';
import { cn } from '@utils/index';
import toast from 'react-hot-toast';

const Settings: React.FC = () => {
  const config = useConfig();
  const { setConfig } = useAppActions();
  const { updateConfig, loading } = useAppConfig();
  const { t, changeLanguage, currentLanguage } = useTranslation();
  const [localConfig, setLocalConfig] = useState(config);
  const [isLanguageChanging, setIsLanguageChanging] = useState(false);
  const [previewLanguage, setPreviewLanguage] = useState<string | null>(null);

  const handleLanguagePreview = async (language: string) => {
    if (language !== currentLanguage) {
      try {
        setPreviewLanguage(language);
        await changeLanguage(language as any);
        toast.success('Language preview activated. Save to make permanent.', {
          duration: 4000,
          icon: '👀',
        });
      } catch (error) {
        console.error('Failed to preview language:', error);
        toast.error('Failed to preview language');
        setPreviewLanguage(null);
      }
    }
  };

  const handleConfigChange = async (key: string, value: any) => {
    const newConfig = {
      ...localConfig,
      [key]: value,
    };

    setLocalConfig(newConfig);

    // If language is being changed, update both i18n and backend config
    if (key === 'language') {
      try {
        setIsLanguageChanging(true);

        // Show loading toast
        const loadingToast = toast.loading('Changing language...');

        // Update i18n store immediately for preview
        await changeLanguage(value as any);

        // Save to backend configuration
        await updateConfig(newConfig);

        // Dismiss loading toast and show success
        toast.dismiss(loadingToast);
        const languageName =
          SUPPORTED_LANGUAGES[value as keyof typeof SUPPORTED_LANGUAGES];
        toast.success(`Language changed to ${languageName}`, {
          duration: 3000,
          icon: '🌐',
        });

        // Force a small delay to ensure UI updates
        setTimeout(() => {
          setIsLanguageChanging(false);
        }, 500);
      } catch (error) {
        console.error('Failed to change language:', error);
        toast.error('Failed to change language', {
          duration: 4000,
          icon: '❌',
        });

        // Revert local config on error
        setLocalConfig(localConfig);
        setIsLanguageChanging(false);
      }
    } else {
      // For other config changes, save to backend
      try {
        const loadingToast = toast.loading('Saving settings...');
        await updateConfig(newConfig);
        toast.dismiss(loadingToast);
        toast.success('Settings saved', {
          duration: 2000,
          icon: '✅',
        });
      } catch (error) {
        console.error('Failed to save settings:', error);
        toast.error('Failed to save settings', {
          duration: 4000,
          icon: '❌',
        });

        // Revert local config on error
        setLocalConfig(localConfig);
      }
    }
  };

  const handleShortcutChange = (
    key: string,
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setLocalConfig(prev => ({
      ...prev,
      shortcuts: {
        ...prev.shortcuts,
        [key]: event.target.value,
      },
    }));
  };

  const handleSave = async () => {
    try {
      // Save configuration to backend
      await updateConfig(localConfig);
      setConfig(localConfig);
      toast.success('Settings saved successfully');
    } catch (error) {
      console.error('Failed to save settings:', error);
      toast.error('Failed to save settings');
    }
  };

  const handleReset = () => {
    setLocalConfig(config);
    toast.success('Settings reset to last saved values');
  };

  const themeOptions = [
    { value: 'light', label: 'Light', icon: SunIcon },
    { value: 'dark', label: 'Dark', icon: MoonIcon },
    { value: 'system', label: 'System', icon: ComputerDesktopIcon },
  ];

  const { supportedLanguages } = useTranslation();

  const languageOptions = Object.entries(supportedLanguages).map(
    ([code, name]) => ({
      value: code,
      label: name,
    })
  );

  return (
    <div className="mx-auto max-w-4xl">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
          {t('settings.title')}
        </h1>
        <p className="mt-2 text-gray-600 dark:text-gray-400">
          {t('settings.subtitle')}
        </p>
      </div>

      <div className="space-y-8">
        {/* Appearance Settings */}
        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="mb-6 flex items-center">
            <SunIcon className="mr-3 h-6 w-6 text-primary-500" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              {t('settings.appearance.title')}
            </h2>
          </div>

          <div className="space-y-6">
            {/* Theme Selection */}
            <div>
              <label className="mb-3 block text-sm font-medium text-gray-700 dark:text-gray-300">
                {t('settings.appearance.theme')}
              </label>
              <div className="grid grid-cols-3 gap-3">
                {themeOptions.map(option => (
                  <button
                    key={option.value}
                    onClick={() => handleConfigChange('theme', option.value)}
                    className={cn(
                      'flex items-center justify-center rounded-lg border-2 p-3 transition-colors',
                      localConfig.theme === option.value
                        ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
                        : 'border-gray-200 hover:border-gray-300 dark:border-gray-700 dark:hover:border-gray-600'
                    )}
                  >
                    <option.icon className="mr-2 h-5 w-5" />
                    <span className="text-sm font-medium">{option.label}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* Language Selection */}
            <div>
              <label className="mb-3 block text-sm font-medium text-gray-700 dark:text-gray-300">
                {t('settings.appearance.language')}
                {isLanguageChanging && (
                  <span className="ml-2 animate-pulse text-xs text-primary-500">
                    Updating...
                  </span>
                )}
              </label>
              <div className="space-y-3">
                <div className="relative">
                  <select
                    value={localConfig.language}
                    onChange={e => {
                      handleConfigChange('language', e.target.value);
                      handleLanguagePreview(e.target.value);
                    }}
                    disabled={isLanguageChanging}
                    className={cn(
                      'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100',
                      isLanguageChanging && 'cursor-not-allowed opacity-50'
                    )}
                  >
                    {languageOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  {isLanguageChanging && (
                    <div className="absolute right-3 top-1/2 -translate-y-1/2 transform">
                      <div className="h-4 w-4 animate-spin rounded-full border-b-2 border-primary-500"></div>
                    </div>
                  )}
                </div>
                {previewLanguage && previewLanguage !== config.language && (
                  <div className="rounded border border-amber-200 bg-amber-50 p-2 text-xs text-amber-600 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-400">
                    <span className="font-medium">Preview Mode:</span> Language
                    changed temporarily. Save settings to make it permanent.
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Application Settings */}
        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="mb-6 flex items-center">
            <ShieldCheckIcon className="mr-3 h-6 w-6 text-primary-500" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              Application
            </h2>
          </div>

          <div className="space-y-6">
            {/* Auto Start */}
            <div className="flex items-center justify-between">
              <div>
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Auto Start
                </label>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Start the application automatically when you log in
                </p>
              </div>
              <button
                onClick={() =>
                  handleConfigChange('autoStart', !localConfig.autoStart)
                }
                className={cn(
                  'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
                  localConfig.autoStart
                    ? 'bg-primary-600'
                    : 'bg-gray-200 dark:bg-gray-700'
                )}
              >
                <span
                  className={cn(
                    'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                    localConfig.autoStart ? 'translate-x-6' : 'translate-x-1'
                  )}
                />
              </button>
            </div>

            {/* Minimize to Tray */}
            <div className="flex items-center justify-between">
              <div>
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Minimize to Tray
                </label>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Minimize to system tray instead of taskbar
                </p>
              </div>
              <button
                onClick={() =>
                  handleConfigChange(
                    'minimizeToTray',
                    !localConfig.minimizeToTray
                  )
                }
                className={cn(
                  'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
                  localConfig.minimizeToTray
                    ? 'bg-primary-600'
                    : 'bg-gray-200 dark:bg-gray-700'
                )}
              >
                <span
                  className={cn(
                    'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                    localConfig.minimizeToTray
                      ? 'translate-x-6'
                      : 'translate-x-1'
                  )}
                />
              </button>
            </div>

            {/* Notifications */}
            <div className="flex items-center justify-between">
              <div>
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Notifications
                </label>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Show desktop notifications
                </p>
              </div>
              <button
                onClick={() =>
                  handleConfigChange(
                    'notifications',
                    !localConfig.notifications
                  )
                }
                className={cn(
                  'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
                  localConfig.notifications
                    ? 'bg-primary-600'
                    : 'bg-gray-200 dark:bg-gray-700'
                )}
              >
                <span
                  className={cn(
                    'inline-block h-4 w-4 transform rounded-full bg-white transition-transform',
                    localConfig.notifications
                      ? 'translate-x-6'
                      : 'translate-x-1'
                  )}
                />
              </button>
            </div>
          </div>
        </div>

        {/* Keyboard Shortcuts */}
        <div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="mb-6 flex items-center">
            <KeyIcon className="mr-3 h-6 w-6 text-primary-500" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
              Keyboard Shortcuts
            </h2>
          </div>

          <div className="space-y-4">
            <div>
              <Input
                label="Toggle Window"
                value={localConfig.shortcuts.toggleWindow}
                onChange={value => handleShortcutChange('toggleWindow', value)}
                placeholder="CmdOrCtrl+Shift+H"
                helperText="Global shortcut to show/hide the application window"
              />
            </div>

            <div>
              <Input
                label="New Item"
                value={localConfig.shortcuts.newItem}
                onChange={value => handleShortcutChange('newItem', value)}
                placeholder="CmdOrCtrl+N"
                helperText="Shortcut to create a new item"
              />
            </div>

            <div>
              <Input
                label="Search"
                value={localConfig.shortcuts.search}
                onChange={value => handleShortcutChange('search', value)}
                placeholder="CmdOrCtrl+F"
                helperText="Shortcut to open search"
              />
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex justify-end space-x-4">
          <Button variant="outline" onClick={handleReset}>
            {t('common.reset')}
          </Button>
          <Button onClick={handleSave} loading={loading}>
            {t('common.save')}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Settings;
